package mytaxis.client.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import mytaxis.client.R;
import mytaxis.client.login.Index;
import mytaxis.client.login.Register;
import mytaxis.client.map.ClientMap;
import mytaxis.client.menu.Menu;
import mytaxis.client.service.ComService;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class BookTaxi extends Activity{
	
	private ComService mBoundService;
	private Button Book;
	private EditText EditAddress;
	private EditText EditCity;
	private DatePicker Date;
	private TimePicker Time;
	private MyTaxisClientApplication app;
	private String URL = "http://maps.google.com/maps/geo?q=";
	

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
		    mBoundService = ((ComService.LocalBinder)service).getService();
		}
	
		public void onServiceDisconnected(ComponentName className) {
		    mBoundService = null;
		}
		};
		
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.booktaxi);
		initViews();
		startService(new Intent(BookTaxi.this, ComService.class));
		bindService(new Intent(this, ComService.class), mConnection, Context.BIND_AUTO_CREATE);
		app = (MyTaxisClientApplication) getApplication();
	}
	
	private void MostrarError(String error){
		final AlertDialog alertDialog = new AlertDialog.Builder(BookTaxi.this).create();
		alertDialog.setTitle("Error");
		alertDialog.setMessage(error);
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			 public void onClick(DialogInterface dialog, int which) {
				 alertDialog.cancel();
			 }
		 });
		alertDialog.show();
	}
	
	private void MostrarMissatge(String m){
		final AlertDialog alertDialog = new AlertDialog.Builder(BookTaxi.this).create();
		alertDialog.setTitle("Information");
		alertDialog.setMessage(m);
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			 public void onClick(DialogInterface dialog, int which) {
				 alertDialog.cancel();
			 }
		 });
		alertDialog.show();
	}
	
	private void initViews(){
		EditAddress = (EditText)findViewById(R.id.EditAddress);
		EditCity = (EditText)findViewById(R.id.EditCity);
		Date = (DatePicker)findViewById(R.id.datePicker);
		Time = (TimePicker)findViewById(R.id.timePicker);
		Book = (Button)findViewById(R.id.btnbook);
		
		Book.setOnClickListener(new Button.OnClickListener(){
			
			public void onClick(View v) {
				String day = String.valueOf(Date.getDayOfMonth());
				String month = String.valueOf(Date.getMonth());
				String year = String.valueOf(Date.getYear());
				String data = day+"/"+month+"/"+year;
				String hour = String.valueOf(Time.getCurrentHour());
				String min = String.valueOf(Time.getCurrentMinute());
				String temps = hour +":" +min;
				String mail = app.getEmail();
				String address = EditAddress.getText().toString();
				String city = EditCity.getText().toString();
				address = address.replace(" ", "%20");
				city = city.replace(" ", "%20");
				double posx, posy = 0.0;
				
				String url = URL + address +"%20"+ city + "&output=csv";
				InputStream is = getConnection(url);
				try {
					String res = convertToString(is);
					String r[] = res.split(",");
					if(!r[0].equals("200"))MostrarError("Location not found, try again");
					else{
						posy = Double.parseDouble(r[2]);
						posx = Double.parseDouble(r[3]);
						String result = mBoundService.DemanarTaxiHoraiLloc(mail, posx, posy, temps, data);
						if (result.contains("-2"))MostrarError("There are no availables taxis right now, please try it later");
						else if (result.contains("-3") || result.contains("-1") || result.contains("-4")) MostrarError("Error connecting to the server, please try again");
						else{
							Thread t = new Thread(){
								public void run(){
									try{
										MostrarMissatge("Taxi assigned, you can consult your requests in your Booking Props");
										sleep(3);

										Intent i = new Intent(BookTaxi.this, Menu.class);
										startActivity(i);
									}
									catch(Exception e){
										Log.d("exc",e.toString());
									}
								};
							};
							t.start();;
						}
					}
					Log.d("res",res);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		
		});
	}  
	
	private String convertToString (InputStream is) throws IOException {
		
		if (is != null) {
			
			Writer writer = new StringWriter();
			
			char[] buffer = new char[1024];

			try {

				Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				int n;
			
			while ((n = reader.read(buffer)) != -1) {
			
			writer.write(buffer, 0, n);
			
			}
			
			} finally {
			
			is.close();
			
			}
			
			return writer.toString();
			
			} else {        
			
			return "";
			
			}
	}
	
	
	private InputStream getConnection(String url) {
		InputStream is = null;
		try {
			URLConnection conn = new URL(url).openConnection();
			is = conn.getInputStream();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}    

}
